package com.cms.action;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import com.action.DefaultAction;
import com.cms.manager.CategoryManager;
import com.cms.manager.CpInfoManager;
import com.cms.model.AppChannelApkInfo;
import com.cms.model.AppInfo;
import com.cms.model.AppScreenshot;
import com.cms.model.AppVersionInfo;
import com.cms.model.AppversionTerraceInfo;
import com.cms.model.Category;
import com.cms.model.Channel;
import com.cms.model.CpInfo;
import com.cms.model.Project;
import com.cms.service.AppChannelApkInfoService;
import com.cms.service.AppChannelApkInfoServiceImpl;
import com.cms.service.AppInfoService;
import com.cms.service.AppInfoServiceImpl;
import com.cms.service.AppVersionInfoService;
import com.cms.service.AppVersionInfoServiceImpl;
import com.cms.service.ChannelService;
import com.cms.service.ChannelServiceImpl;
import com.cms.service.ProjectService;
import com.cms.service.ProjectServiceImpl;
import com.model.Admin;
import com.util.Config;
import com.util.ConfigUtil;
import com.util.FileDigest;
import com.util.Util;
import com.xuanzhi.ms.server.logic.channel.ChannelManager;


/**   
 *   
 * @author zhanghusong   
 */
public class AppChannelApkInfoAction extends DefaultAction {

	private static final long serialVersionUID = 1L;
	
	public AppChannelApkInfoAction()
	{
	}
	AppChannelApkInfo model;
	AppChannelApkInfoService service = new AppChannelApkInfoServiceImpl();
	AppInfoService appservice = new AppInfoServiceImpl();
	AppVersionInfoService appversionservice = new AppVersionInfoServiceImpl();
	List<AppChannelApkInfo> list;
	String type="";
	String msg="";
	List<AppInfo> applist;
	List<AppVersionInfo> appversionlist;
	String appid;
	int appversionid;
	int channelid;
	int projectid;
	String appname;
	AppVersionInfo appversion;
	List<Channel> channellist;
	List<CpInfo> cplist;
	List<Project> projectlist;
	List<AppversionTerraceInfo> apvtlist;
	ChannelService channelservice = new ChannelServiceImpl();
	ProjectService projectservice = new ProjectServiceImpl();
	List<Category> caplist;
	List<AppVersionInfo> appversionlist1;
	private List<AppScreenshot> aslist;
	private File Filedata;
	private String FiledataFileName;
	private String FiledataContentType;
	private String appscreenshotid;
	private String appscreenshoturl;
	public String list()
	{
		applist = appservice.getAppInfos();  
		channellist = channelservice.getChannels();
		apvtlist = appversionservice.queryAppversionTerrace();
		Admin admin = getAdmin();
		if(!"true".equals(admin.getIsAdmin())){
			list = service.getAppChannelApksByAdmin(admin);
		}else{
			list = service.getAppChannelApkInfos(appid, appversionid, channelid, projectid, appname);
		}
		cplist = CpInfoManager.getInstance().getCpInfos();
		if(appid!=null && appid.length()>0)
		{
			appversionlist = appversionservice.getAppVersionInfoByAppNumber(appid);
		}
		projectlist = projectservice.getProjects();
		caplist = CategoryManager.getInstance().getCategorys();
		appversionlist1 = appversionservice.getAppVersionInfos();
		return SUCCESS;
	}
	public String show()
	{
		applist = appservice.getAppInfos();
		channellist = channelservice.getChannels();
		if(type.equals("update"))
		{
			model = service.getAppChannelApkInfoById(model.getId());
			String channelapkid = model.getChannelapkid(),
				   tmp_channelapkid=channelapkid;
			if(channelapkid!=null&&!"".equals(channelapkid)){
				if(channelapkid.indexOf("-")!=-1){
					tmp_channelapkid = channelapkid.split("-", 2)[1];
				}
			}
			model.setChannelapkid(tmp_channelapkid);
			//aslist = appservice.getAppScreenshotBychannelapkNumber(model.getChannelapknumber(),null);
			if(model.getChannelid()>0)
			{
				projectlist = projectservice.getProjects(model.getChannelid());
			}
			
			if(model.getAppnumber()!=null && model.getAppnumber().length()>0)
			{
				appversionlist = appversionservice.getAppVersionInfoByAppNumber(model.getAppnumber());
			}
		}
		else
		{
			model = new AppChannelApkInfo();
			model.setId(-1);
			model.setChannelapknumber(Util.genAppNumber());
		}
		return SUCCESS;
	}
	public String save()
	{
		model.setChannelapkid(model.getChannelid()+"-"+model.getChannelapkid());
		if(type.equals("insert"))
		{			
			model.setCreateuser(getAdminLoginName());
			model.setCreatedate(Util.dateToString(new Date()));
			model.setAppmd5(model.getRefilename());
			if(service.saveAppChannelApkInfo(model))
				msg = "渠道包管理：添加成功";
			else
				msg = "渠道包管理：添加失败！请重新添加！";
		}
		else if(type.equals("update"))
		{
			model.setAppmd5(model.getRefilename());
			if(service.updateAppChannelApkInfo(model))
				msg = "渠道包管理：更新成功！";
			else
				msg = "渠道包管理：更新失败！请重新更新！";
			type = "upd";
		}
		else if(type.equals("del"))
		{
			if(service.deleteAppChannelApkInfo(model))
				msg = "渠道包管理：删除成功！";
			else
				msg = "渠道包管理：删除失败！请重新删除！";
		}
		return SUCCESS;
	}
	
	public String saveoffonline()
	{
		service.saveAppChannelApkInfoStatus(model);
		return SUCCESS;
	}
	public String uploadapp()
	{
		if(Filedata!=null)
		{
			String reiconname = FileDigest.getFileMD5(Filedata);
			String filesrc = ConfigUtil.get(Config.SECTIONMANAGE, Config.KEY_CP_APP_SAVE_PATH) + 
			"/"+reiconname;
			saveUploadFile(Filedata,filesrc);
			String appchannelapknumber = model.getChannelapknumber();
			AppScreenshot as = new AppScreenshot();
			as.setId(-1);
			as.setGenre("2");
			as.setType("4"); //代表apk
			as.setAppnumber(model.getAppnumber());
			as.setAppversionnumber(model.getAppversionnumber());
			as.setChannelappnumber(appchannelapknumber);
			as.setImgname(FiledataFileName);
			as.setImgrename(reiconname);
			as.setImgsrc(filesrc);
			appservice.saveAppScreenshot(as);
			appscreenshotid = ""+as.getId();
			appscreenshoturl = reiconname;
			model = new AppChannelApkInfo();
			model.setRefilename(FiledataFileName);
		}
		return SUCCESS;
	}
	
	public String uploadicon()
	{
		if(Filedata!=null)
		{
			String reiconname = FileDigest.getFileMD5(Filedata);
			String filesrc = ConfigUtil.get(Config.SECTIONMANAGE, Config.KEY_CP_APP_SAVE_PATH) + 
			"/icon/";
			File f = new File(filesrc);
			if(!f.exists()){
				f.mkdir();
			}
			filesrc+=reiconname;
			saveUploadFile(Filedata,filesrc);
			AppScreenshot as = new AppScreenshot();
			as.setId(-1);
			as.setGenre("2");
			as.setType("0");
			as.setAppnumber(model.getAppnumber());
			as.setAppversionnumber(model.getAppversionnumber());
			as.setChannelappnumber(model.getChannelapknumber());
			as.setImgname(FiledataFileName);
			as.setImgrename(reiconname);
			as.setImgsrc(filesrc);
			appservice.saveAppScreenshot(as);
			appscreenshotid = ""+as.getId();
			appscreenshoturl = reiconname;
			
		}
		return SUCCESS;
	}
	public String uploadremark()
	{
		if(Filedata!=null)
		{
			String reiconname = FileDigest.getFileMD5(Filedata);
			String filesrc = ConfigUtil.get(Config.SECTIONMANAGE, Config.KEY_CP_APP_SAVE_PATH) + 
			"/remark/";
			File f = new File(filesrc);
			if(!f.exists()){
				f.mkdir();
			}
			filesrc+=reiconname;
			saveUploadFile(Filedata,filesrc);
			AppScreenshot as = new AppScreenshot();
			as.setId(-1);
			as.setGenre("2");
			as.setType("1");
			as.setAppnumber(model.getAppnumber());
			as.setAppversionnumber(model.getAppversionnumber());
			as.setChannelappnumber(model.getChannelapknumber());
			as.setImgname(FiledataFileName);
			as.setImgrename(reiconname);
			as.setImgsrc(filesrc);
			appservice.saveAppScreenshot(as);
			appscreenshotid = ""+as.getId();
			appscreenshoturl = reiconname;
			model = new AppChannelApkInfo();
			model.setRefilename(FiledataFileName);
		}
		return SUCCESS;
	}
	public String uploadremark1()
	{
		if(Filedata!=null)
		{
			String reiconname = FileDigest.getFileMD5(Filedata);
			String filesrc = ConfigUtil.get(Config.SECTIONMANAGE, Config.KEY_CP_APP_SAVE_PATH) + 
			"/remark1/";
			File f = new File(filesrc);
			if(!f.exists()){
				f.mkdir();
			}
			filesrc+=reiconname;
			saveUploadFile(Filedata,filesrc);
			AppScreenshot as = new AppScreenshot();
			as.setId(-1);
			as.setGenre("2");
			as.setType("3");
			as.setAppnumber(model.getAppnumber());
			as.setAppversionnumber(model.getAppversionnumber());
			as.setChannelappnumber(model.getChannelapknumber());
			as.setImgname(FiledataFileName);
			as.setImgrename(reiconname);
			as.setImgsrc(filesrc);
			appservice.saveAppScreenshot(as);
			appscreenshotid = ""+as.getId();
			appscreenshoturl = reiconname;
			model = new AppChannelApkInfo();
			model.setRefilename(FiledataFileName);
		}
		return SUCCESS;
	}
	public String uploadscreenshot()
	{
		if(Filedata!=null)
		{
			String reiconname = FileDigest.getFileMD5(Filedata);
			String filesrc = ConfigUtil.get(Config.SECTIONMANAGE, Config.KEY_CP_APP_SAVE_PATH) + 
			"/";
			File f = new File(filesrc);
			if(!f.exists()){
				f.mkdir();
			}
			filesrc+=reiconname;
			saveUploadFile(Filedata,filesrc);
			AppScreenshot as = new AppScreenshot();
			as.setId(-1);
			as.setGenre("2"); //1代表渠道包信息
			as.setType("2");
			as.setAppnumber(model.getAppnumber());
			as.setAppversionnumber(model.getAppversionnumber());
			as.setChannelappnumber(model.getChannelapknumber());
			as.setImgname(FiledataFileName);
			as.setImgrename(reiconname);
			as.setImgsrc(filesrc);
			appservice.saveAppScreenshot(as);
			aslist = appservice.getAppScreenshotBychannelapkNumber(model.getChannelapknumber(),null);
			appscreenshotid = ""+as.getId();
			appscreenshoturl = reiconname;
		}
		return SUCCESS;
	}
	//下载apk
	public  void downApp(){
		AppChannelApkInfo info=null;
		
		if(model.getId()>0){
			 info= service.getAppChannelApkInfoById(model.getId());
		}		
		String path=info.getAppfilesrc();//文件路径
		if(!path.equals("")){
			// path是指欲下载的文件的路径。
	        File file = new File(path);
	        // 取得文件名。
	        String filename = info.getAppfilename();//file.getName();
	        // 取得文件的后缀名。
	        String ext = filename.substring(filename.lastIndexOf(".") + 1).toUpperCase();
	        try{
		        // 以流的形式下载文件。
		        InputStream fis = new BufferedInputStream(new FileInputStream(path));
		        byte[] buffer = new byte[fis.available()];
		        fis.read(buffer);
		        fis.close();
		        
		        // 清空response
		        this.getResponse().reset();
		        // 设置response的Header
		        this.getResponse().addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes()));
		        this.getResponse().addHeader("Content-Length", "" + file.length());
		        OutputStream toClient = new BufferedOutputStream(this.getResponse().getOutputStream());
		        this.getResponse().setContentType("application/octet-stream");
		        toClient.write(buffer);
		        toClient.flush();
		        toClient.close();
		    } catch (IOException ex) {
		    	ex.printStackTrace();
		    }
			}
		else{
			msg = "您还没有上传apk,请上传aqk";
		}
	}
	public String d()
	{
		try {
			HttpServletResponse response = super.getResponse();
			InputStream is = new BufferedInputStream(new FileInputStream(ConfigUtil.get(Config.SECTIONMANAGE, Config.KEY_CP_APP_SAVE_PATH) + 
					"/"+appscreenshoturl));
			byte[] b = new byte[is.available()];
			is.read(b);
			is.close();			
			String fileName = model.getAppfilename();
	    	response.setContentType("application/octet-stream");
	    	response.setHeader("Location", fileName);
	    	response.setHeader("Content-Disposition", "attachment; filename=" + new String(fileName.getBytes("gb2312"), "ISO8859-1"));
	    	OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
	    	outputStream.write(b);
	    	outputStream.flush();
	    	outputStream.close();
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		return null;
	}
	public String changeapp()
	{
		appversionlist = appversionservice.getAppVersionInfoByAppNumber(model.getAppnumber());
		//取平台名称和版本代码		
		List<AppversionTerraceInfo> l = appversionservice.queryAppversionTerrace();
		for (AppVersionInfo apv : appversionlist) {
			for (AppversionTerraceInfo apvt : l) {
				if(apvt.getAppversionId()!=apv.getId()){continue;}
				apv.setAppname(apv.getAppname()+"("+apvt.getOperatorsName()+")");
			}
		}
		return SUCCESS;
	}
	public String changechannel()
	{
		projectlist = projectservice.getProjects(channelid);
		return SUCCESS;
	}
	String appversionstr="";
	public String changeappversion()
	{
		appversion = appversionservice.getAppVersionInfoById(appversion.getId());
		StringBuffer sb = new StringBuffer("");
		sb.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
		sb.append("<appversion>");
		sb.append("<id>"+appversion.getId()+"</id>");
		sb.append("<appversionnumber>"+appversion.getAppversionnumber()+"</appversionnumber>");
		sb.append("<appnumber>"+appversion.getAppnumber()+"</appnumber>");
		sb.append("<appname>"+appversion.getAppname()+"</appname>");
		sb.append("<cpid>"+appversion.getCpid()+"</cpid>");
		sb.append("<categoryparentid>"+appversion.getCategoryparentid()+"</categoryparentid>");
		sb.append("<categoryid>"+appversion.getCategoryid()+"</categoryid>");
		sb.append("<apppackage>"+appversion.getApppackage()+"</apppackage>");
		sb.append("<appstatus>"+appversion.getAppstatus()+"</appstatus>");
		sb.append("<appversion>"+appversion.getAppversion()+"</appversion>");
		sb.append("<appmd5>"+appversion.getAppmd5()+"</appmd5>");
		sb.append("<appiconname>"+appversion.getAppiconname()+"</appiconname>");
		sb.append("<reiconname>"+appversion.getReiconname()+"</reiconname>");
		sb.append("<appiconsrc>"+appversion.getAppiconsrc()+"</appiconsrc>");
		sb.append("<appfilename>"+appversion.getAppfilename()+"</appfilename>");
		sb.append("<refilename>"+appversion.getRefilename()+"</refilename>");
		sb.append("<appfilesrc>"+appversion.getAppfilesrc()+"</appfilesrc>");
		sb.append("<appentry>"+appversion.getAppentry()+"</appentry>");
		sb.append("<createuser>"+appversion.getCreateuser()+"</createuser>");
		sb.append("<createdate>"+appversion.getCreatedate()+"</createdate>");
		sb.append("<appremark>"+appversion.getAppremark()+"</appremark>");
		sb.append("</appversion>");
		appversionstr = sb.toString();
		return SUCCESS;
	}
	public String changeappxml()
	{
		appversionlist = appversionservice.getAppVersionInfoByAppNumber(appid);
		StringBuffer sb = new StringBuffer("");
		sb.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
		sb.append("<list>");
		if(appversionlist!=null && appversionlist.size()>0)
		{
			for(int i =0;i<appversionlist.size();i++)
			{
				appversion = appversionlist.get(i);
				sb.append("<appversion>");
				sb.append("<id>"+appversion.getId()+"</id>");
				sb.append("<appnumber>"+appversion.getAppnumber()+"</appnumber>");
				sb.append("<appname>"+appversion.getAppname()+"</appname>");
				sb.append("</appversion>");
			}
		}
		sb.append("</list>");
		appversionstr = sb.toString();
		return SUCCESS;
	}
	public String showpack(){
		model = service.getAppChannelApkInfoById(model.getId());
		String tmps = model.getChannelapkid();
		model.setChannelapkid(tmps.split("-")[1]);
		applist = appservice.getAppInfos();
		channellist = channelservice.getChannels();
		appversionlist = appversionservice.getAppVersionInfos();
		return SUCCESS;
	}
	public String scalelist(){
		channellist = channelservice.getChannels();
		list = service.getAppChannelApkInfos();
		return SUCCESS;
	}
	public void changescale(){
		String s = "no";
		if(service.changescale(model)){
			s="ok";
		}
		try {
			PrintWriter pw = getResponse().getWriter();
			pw.write(s);
			pw.flush();
			pw.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	public String getAppscreenshotid() {
		return appscreenshotid;
	}
	public void setAppscreenshotid(String appscreenshotid) {
		this.appscreenshotid = appscreenshotid;
	}
	public String getAppscreenshoturl() {
		return appscreenshoturl;
	}
	public void setAppscreenshoturl(String appscreenshoturl) {
		this.appscreenshoturl = appscreenshoturl;
	}
	public String getType() {
		return type;
	}
	public void setType(String type) {
		this.type = type;
	}
	public String getMsg() {
		return msg;
	}
	public void setMsg(String msg) {
		this.msg = msg;
	}
	public File getFiledata() {
		return Filedata;
	}
	public void setFiledata(File filedata) {
		Filedata = filedata;
	}
	public String getFiledataFileName() {
		return FiledataFileName;
	}
	public void setFiledataFileName(String filedataFileName) {
		FiledataFileName = filedataFileName;
	}
	public String getFiledataContentType() {
		return FiledataContentType;
	}
	public void setFiledataContentType(String filedataContentType) {
		FiledataContentType = filedataContentType;
	}
	public AppChannelApkInfo getModel() {
		return model;
	}
	public void setModel(AppChannelApkInfo model) {
		this.model = model;
	}
	public List<AppChannelApkInfo> getList() {
		return list;
	}
	public void setList(List<AppChannelApkInfo> list) {
		this.list = list;
	}
	public List<AppInfo> getApplist() {
		return applist;
	}
	public void setApplist(List<AppInfo> applist) {
		this.applist = applist;
	}
	public List<AppVersionInfo> getAppversionlist() {
		return appversionlist;
	}
	public void setAppversionlist(List<AppVersionInfo> appversionlist) {
		this.appversionlist = appversionlist;
	}
	
	public String getAppid() {
		return appid;
	}
	public void setAppid(String appid) {
		this.appid = appid;
	}
	public int getAppversionid() {
		return appversionid;
	}
	public void setAppversionid(int appversionid) {
		this.appversionid = appversionid;
	}
	public int getChannelid() {
		return channelid;
	}
	public void setChannelid(int channelid) {
		this.channelid = channelid;
	}
	public int getProjectid() {
		return projectid;
	}
	public void setProjectid(int projectid) {
		this.projectid = projectid;
	}
	public String getAppname() {
		return appname;
	}
	public void setAppname(String appname) {
		this.appname = appname;
	}
	public AppVersionInfo getAppversion() {
		return appversion;
	}
	public void setAppversion(AppVersionInfo appversion) {
		this.appversion = appversion;
	}
	public String getAppversionstr() {
		return appversionstr;
	}
	public void setAppversionstr(String appversionstr) {
		this.appversionstr = appversionstr;
	}
	public List<Channel> getChannellist() {
		return channellist;
	}
	public void setChannellist(List<Channel> channellist) {
		this.channellist = channellist;
	}
	public List<Project> getProjectlist() {
		return projectlist;
	}
	public void setProjectlist(List<Project> projectlist) {
		this.projectlist = projectlist;
	}
	public List<CpInfo> getCplist() {
		return cplist;
	}
	public void setCplist(List<CpInfo> cplist) {
		this.cplist = cplist;
	}
	public List<Category> getCaplist() {
		return caplist;
	}
	public void setCaplist(List<Category> caplist) {
		this.caplist = caplist;
	}
	public List<AppVersionInfo> getAppversionlist1() {
		return appversionlist1;
	}
	public void setAppversionlist1(List<AppVersionInfo> appversionlist1) {
		this.appversionlist1 = appversionlist1;
	}
	public List<AppScreenshot> getAslist() {
		return aslist;
	}
	public void setAslist(List<AppScreenshot> aslist) {
		this.aslist = aslist;
	}
	public List<AppversionTerraceInfo> getApvtlist() {
		return apvtlist;
	}
	public void setApvtlist(List<AppversionTerraceInfo> apvtlist) {
		this.apvtlist = apvtlist;
	}
	
}
